package org.glow.changgou.seckill.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.glow.changgou.entity.IdWorker;
import org.glow.changgou.entity.StatusCode;
import org.glow.changgou.entity.SystemConstants;
import org.glow.changgou.seckill.dao.SeckillGoodsMapper;
import org.glow.changgou.seckill.dao.SeckillOrderMapper;
import org.glow.changgou.seckill.pojo.SeckillGoods;
import org.glow.changgou.seckill.pojo.SeckillOrder;
import org.glow.changgou.seckill.pojo.SeckillStatus;
import org.glow.changgou.seckill.service.SeckillOrderService;
import org.glow.changgou.seckill.task.MultiThreadingCreateOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/****
 * @Author:glow
 * @Description:SeckillOrder业务层接口实现类
 *****/
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper,SeckillOrder> implements SeckillOrderService {

    @Resource
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private MultiThreadingCreateOrder multiThreadingCreateOrder;

    /**
     * SeckillOrder条件+分页查询
     * @param seckillOrder 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<SeckillOrder> findPage(SeckillOrder seckillOrder, int page, int size){
       Page<SeckillOrder> pageInfo = new Page<>(page,size);
       LambdaQueryWrapper<SeckillOrder> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper = getCondition(queryWrapper,seckillOrder);
       return seckillOrderMapper.selectPage(pageInfo,queryWrapper);
    }

    /**
     * SeckillOrder分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<SeckillOrder> findPage(int page, int size){
        Page<SeckillOrder> pageInfo = new Page<>(page,size);

        return seckillOrderMapper.selectPage(pageInfo,null);
    }

    /**
     * SeckillOrder条件查询
     * @param seckillOrder
     * @return
     */
    @Override
    public List<SeckillOrder> findList(SeckillOrder seckillOrder){
        LambdaQueryWrapper<SeckillOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = getCondition(queryWrapper,seckillOrder);
        return seckillOrderMapper.selectList(queryWrapper);
    }


    /**
     * SeckillOrder构建查询对象
     * @param seckillOrder
     * @return
     */
    public LambdaQueryWrapper<SeckillOrder> getCondition(LambdaQueryWrapper<SeckillOrder> queryWrapper, SeckillOrder seckillOrder){

        if(seckillOrder!=null){
            // 主键
            if(!StringUtils.isEmpty(seckillOrder.getId())){
//                    criteria.andEqualTo("id",seckillOrder.getId());
                    queryWrapper.eq(SeckillOrder::getId,seckillOrder.getId());
            }
            // 秒杀商品ID
            if(!StringUtils.isEmpty(seckillOrder.getSeckillId())){
//                    criteria.andEqualTo("seckillId",seckillOrder.getSeckillId());
                    queryWrapper.eq(SeckillOrder::getSeckillId,seckillOrder.getSeckillId());
            }
            // 支付金额
            if(!StringUtils.isEmpty(seckillOrder.getMoney())){
//                    criteria.andEqualTo("money",seckillOrder.getMoney());
                    queryWrapper.eq(SeckillOrder::getMoney,seckillOrder.getMoney());
            }
            // 用户
            if(!StringUtils.isEmpty(seckillOrder.getUserId())){
                queryWrapper.eq(SeckillOrder::getUserId,seckillOrder.getUserId());
//                    criteria.andEqualTo("userId",seckillOrder.getUserId());
//                    queryWrapper
            }
            // 创建时间
            if(!StringUtils.isEmpty(seckillOrder.getCreateTime())){
//                    criteria.andEqualTo("createTime",seckillOrder.getCreateTime());
                    queryWrapper.eq(SeckillOrder::getCreateTime,seckillOrder.getCreateTime());
            }
            // 支付时间
            if(!StringUtils.isEmpty(seckillOrder.getPayTime())){
//                    criteria.andEqualTo("payTime",seckillOrder.getPayTime());
                    queryWrapper.eq(SeckillOrder::getPayTime,seckillOrder.getPayTime());
            }
            // 状态，0未支付，1已支付
            if(!StringUtils.isEmpty(seckillOrder.getStatus())){
//                    criteria.andEqualTo("status",seckillOrder.getStatus());
                    queryWrapper.eq(SeckillOrder::getStatus,seckillOrder.getStatus());
            }
            // 收货人地址
            if(!StringUtils.isEmpty(seckillOrder.getReceiverAddress())){
                queryWrapper.eq(SeckillOrder::getReceiverAddress,seckillOrder.getReceiverAddress());
//                    criteria.andEqualTo("receiverAddress",seckillOrder.getReceiverAddress());
            }
            // 收货人电话
            if(!StringUtils.isEmpty(seckillOrder.getReceiverMobile())){
//                    criteria.andEqualTo("receiverMobile",seckillOrder.getReceiverMobile());
                    queryWrapper.eq(SeckillOrder::getReceiverMobile,seckillOrder.getReceiverMobile());
            }
            // 收货人
            if(!StringUtils.isEmpty(seckillOrder.getReceiver())){
//                    criteria.andEqualTo("receiver",seckillOrder.getReceiver());
                    queryWrapper.eq(SeckillOrder::getReceiver,seckillOrder.getReceiver());
            }
            // 交易流水
            if(!StringUtils.isEmpty(seckillOrder.getTransactionId())){
//                    criteria.andEqualTo("transactionId",seckillOrder.getTransactionId());
                    queryWrapper.eq(SeckillOrder::getTransactionId,seckillOrder.getTransactionId());
            }
        }
        return queryWrapper;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Long id){
        seckillOrderMapper.deleteById(id);
    }

    /**
     * 修改SeckillOrder
     * @param seckillOrder
     */
    @Override
    public void update(SeckillOrder seckillOrder){
        seckillOrderMapper.updateById(seckillOrder);
    }

    /**
     * 增加SeckillOrder
     * @param seckillOrder
     */
    @Override
    public void add(SeckillOrder seckillOrder){
        seckillOrderMapper.insert(seckillOrder);
    }

    /**
     * 根据ID查询SeckillOrder
     * @param id
     * @return
     */
    @Override
    public SeckillOrder findById(Long id){
        return  seckillOrderMapper.selectById(id);
    }

    /**
     * 查询SeckillOrder全部数据
     * @return
     */
    @Override
    public List<SeckillOrder> findAll() {
        return seckillOrderMapper.selectList(null);
    }


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Resource
    private SeckillGoodsMapper seckillGoodsMapper;



    @Override
    public boolean add(Long id, String time, String username) {
        Long userQueueCount = redisTemplate.boundHashOps("UserQueueCount").increment(username, 1);
        if(userQueueCount>1){
            //100：表示有重复抢单
            throw new RuntimeException(String.valueOf(StatusCode.REPERROR));
        }
        //排队信息封装
        SeckillStatus seckillStatus = new SeckillStatus(username, new Date(),1, id,time);
        //将秒杀抢单信息存入到Redis中,这里采用List方式存储,List本身是一个队列
        redisTemplate.boundListOps("SeckillOrderQueue").leftPush(seckillStatus);
        //将抢单状态存入到Redis中
        redisTemplate.boundHashOps("UserQueueStatus").put(username,seckillStatus);
    multiThreadingCreateOrder.createrOrder();
        return true;
    }

    /**
     * 抢单状态查询
     * @param username
     * @return
     */
    @Override
    public SeckillStatus queryStatus(String username) {
      return (SeckillStatus) redisTemplate.boundHashOps("UserQueueStatus").get(username);
    }
    @Transactional
    @Override
    public void updatePayStatus(String out_trade_no, String transaction_id, String username) {
        //订单数据从Redis数据库查询出来
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.boundHashOps("SeckillOrder").get(username);
        //修改状态
        seckillOrder.setStatus("1");

        //支付时间
        seckillOrder.setPayTime(new Date());
        //同步到MySQL中
        seckillOrderMapper.insert(seckillOrder);

        //清空Redis缓存
        redisTemplate.boundHashOps("SeckillOrder").delete(username);

        //清空用户排队数据
        redisTemplate.boundHashOps("UserQueueCount").delete(username);

        //删除抢购状态信息
        redisTemplate.boundHashOps("UserQueueStatus").delete(username);
    }

    /***
     * 关闭订单，回滚库存
     * @param username
     */
    @Override
    public void closeOrder(String username) {
        //将消息转换成SeckillStatus
        SeckillStatus seckillStatus = (SeckillStatus) redisTemplate.boundHashOps("UserQueueStatus").get(username);
        //获取Redis中订单信息
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.boundHashOps("SeckillOrder").get(username);

        //如果Redis中有订单信息，说明用户未支付
        if(seckillStatus!=null && seckillOrder!=null){
            //删除订单
            redisTemplate.boundHashOps("SeckillOrder").delete(username);
            //回滚库存
            //1)从Redis中获取该商品
            SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_"+seckillStatus.getTime()).get(seckillStatus.getGoodsId());

            //2)如果Redis中没有，则从数据库中加载
            if(seckillGoods==null){
                seckillGoods = seckillGoodsMapper.selectById(seckillStatus.getGoodsId());
            }

            //3)数量+1  (递增数量+1，队列数量+1)
            Long surplusCount = redisTemplate.boundHashOps("SeckillGoodsCount").increment(seckillStatus.getGoodsId(), 1);
            seckillGoods.setStockCount(surplusCount.intValue());
            redisTemplate.boundListOps("SeckillGoodsCountList_" + seckillStatus.getGoodsId()).leftPush(seckillStatus.getGoodsId());

            //4)数据同步到Redis中
            redisTemplate.boundHashOps("SeckillGoods_"+seckillStatus.getTime()).put(seckillStatus.getGoodsId(),seckillGoods);

            //清理排队标示
            redisTemplate.boundHashOps("UserQueueCount").delete(seckillStatus.getUsername());

            //清理抢单标示
            redisTemplate.boundHashOps("UserQueueStatus").delete(seckillStatus.getUsername());
        }
    }
}
